package com.zhihuishu.micro.course.openapi.app.impl.teacher;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhihuishu.micro.course.dto.CategoryDto;
import com.zhihuishu.micro.course.dto.CourseCategoryDto;
import com.zhihuishu.micro.course.log.LoggerCollectionEnum;
import com.zhihuishu.micro.course.log.LoggerTemplateUtil;
import com.zhihuishu.micro.course.openapi.app.dto.CategoryOpenDto;
import com.zhihuishu.micro.course.openapi.app.dto.CourseCategoryOpenDto;
import com.zhihuishu.micro.course.openapi.app.teacher.CourseCategoryOpenService;
import com.zhihuishu.micro.course.service.CategoryService;
import com.zhihuishu.micro.course.service.CourseService;
import com.zhihuishu.myuni.openapi.course.ICourseRemoteService;
import com.zhihuishu.myuni.openapi.course.dto.CourseWebDto;
import com.zhihuishu.remote.ErrorCode;
import com.zhihuishu.remote.RemoteResult;
import com.zhihuishu.toolkit.helper.BeanHelper;

@Service("courseCategoryOpenServiceForTeacherApp")
public class CourseCategoryOpenServiceImpl implements CourseCategoryOpenService {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private CategoryService categoryService;

    @Resource
    private CourseService courseService;

    @Resource
    private ICourseRemoteService myuniCourseRemoteService;

    @Override
    public RemoteResult<List<CourseCategoryOpenDto>> queryCategoriesByCourseId(long courseId) {
        RemoteResult<List<CourseCategoryOpenDto>> remoteResult = new RemoteResult<List<CourseCategoryOpenDto>>();
        try {
            List<CourseCategoryDto> list = categoryService.listByCourse(courseId);
            if (logger.isDebugEnabled()) {
                logger.debug("查询到课程{}的课程分类信息为{}", courseId, list);
            }
            if (!CollectionUtils.isEmpty(list)) {
                List<CourseCategoryOpenDto> target = new ArrayList<CourseCategoryOpenDto>();
                for (CourseCategoryDto ccd : list) {
                    CourseCategoryOpenDto ccod = new CourseCategoryOpenDto();
                    ccod.setId(ccd.getId());
                    ccod.setCourseId(ccd.getCourseId());
                    ccod.setFirstId(ccd.getFirstId());
                    ccod.setSecondId(ccd.getSecondId());
                    ccod.setThirdId(ccd.getThirdId());
                    ccod.setFirst(BeanHelper.transTo(ccd.getFirst(), CategoryOpenDto.class));
                    ccod.setSecond(BeanHelper.transTo(ccd.getSecond(), CategoryOpenDto.class));
                    ccod.setThird(BeanHelper.transTo(ccd.getThird(), CategoryOpenDto.class));
                    target.add(ccod);
                }
                remoteResult.setResult(target);
            }
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<Integer> createCourseCategory(CourseCategoryOpenDto courseCategory) {
        RemoteResult<Integer> remoteResult = new RemoteResult<Integer>();
        // 参数检查
        if (courseCategory == null || courseCategory.getCourseId() == null
                || courseCategory.getFirstId() == null || courseCategory.getSecondId() == null
                || courseCategory.getThirdId() == null) {
            remoteResult.setSuccess(false);
            remoteResult.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return remoteResult;
        }

        // 执行保存
        try {
            CourseCategoryDto cc = new CourseCategoryDto();
            cc.setCourseId(courseCategory.getCourseId());
            cc.setFirstId(courseCategory.getFirstId());
            cc.setSecondId(courseCategory.getSecondId());
            cc.setThirdId(courseCategory.getThirdId());
            Integer courseCategoryId = categoryService.saveCourseCategory(cc);
            LoggerTemplateUtil.saveLogger(
                    String.format("创建课程分类,courseId=%d,firstId=%d,secondId=%d,thirdId=%d",
                            courseCategory.getCourseId(), courseCategory.getFirstId(),
                            courseCategory.getSecondId(), courseCategory.getThirdId()), 0L,
                    LoggerCollectionEnum.courseCollection, courseCategory.getCourseId());
            if (courseCategoryId == null) {
                remoteResult.setSuccess(false);
                remoteResult.setErrorCode(1);
            }
            remoteResult.setResult(courseCategoryId);
        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }

        return remoteResult;
    }

    @Override
    public RemoteResult<Void> updateCourseCategory(CourseCategoryOpenDto courseCategory) {
        RemoteResult<Void> result = new RemoteResult<Void>();
        // 参数检查
        if (courseCategory == null
                || courseCategory.getId() == null
                || (courseCategory.getFirstId() == null && courseCategory.getSecondId() == null && courseCategory
                        .getThirdId() == null)) {
            result.setSuccess(false);
            result.setErrorCode(ErrorCode.ARGUMENTS_ILLEGALITY);
            return result;
        }

        try {
            // 执行本地更新
            CourseCategoryDto cc = new CourseCategoryDto();
            cc.setId(courseCategory.getId());
            cc.setCourseId(courseCategory.getCourseId());
            cc.setFirstId(courseCategory.getFirstId());
            cc.setSecondId(courseCategory.getSecondId());
            cc.setThirdId(courseCategory.getThirdId());
            categoryService.updateCourseCategory(cc);
            LoggerTemplateUtil.saveLogger(
                    String.format("更新课程分类,courseId=%d,firstId=%d,secondId=%d,thirdId=%d",
                            courseCategory.getCourseId(), courseCategory.getFirstId(),
                            courseCategory.getSecondId(), courseCategory.getThirdId()), 0L,
                    LoggerCollectionEnum.courseCollection, courseCategory.getCourseId());
            // 执行远程更新
            Long myuniCourseId = courseService.getMyuniCourseId(cc.getCourseId());
            if (myuniCourseId != null) {
                CourseWebDto cwd = new CourseWebDto();
                cwd.setOnlineCourseId(cc.getCourseId().intValue());
                cwd.setCateOne(cc.getFirstId());
                cwd.setCateTwo(cc.getSecondId());
                cwd.setCategoryId(cc.getThirdId());
                myuniCourseRemoteService.update(cwd, myuniCourseId);
                LoggerTemplateUtil.saveLogger(String.format(
                        "远程更新myuni课程分类,courseId=%d,firstId=%d,secondId=%d,thirdId=%d",
                        courseCategory.getCourseId(), courseCategory.getFirstId(),
                        courseCategory.getSecondId(), courseCategory.getThirdId()), 0L,
                        LoggerCollectionEnum.courseCollection, courseCategory.getCourseId());
            }

        } catch (Exception e) {

        }

        return result;
    }

    @Override
    public RemoteResult<Void> deleteCourseCategoryById(Integer id) {
        RemoteResult<Void> remoteResult = new RemoteResult<Void>();
        try {
            Assert.notNull(id, "删除课程分类标签id不能为空");
            categoryService.deleteById(id);
            LoggerTemplateUtil.saveLogger(String.format("删除课程分类标签,categoryId=%d", id), 0L,
                    LoggerCollectionEnum.courseCollection);
        } catch (Exception e) {
            remoteResult.setSuccess(false);
            remoteResult.setExceptionStack(e);
        }
        return remoteResult;
    }

    @Override
    public RemoteResult<List<CategoryOpenDto>> queryAllCatergoryInfo() {
        RemoteResult<List<CategoryOpenDto>> remoteResult = new RemoteResult<List<CategoryOpenDto>>();
        try {
            List<CategoryDto> categoryDtos = categoryService.listAllLables();
            List<CategoryOpenDto> labelOpenDtos = BeanHelper.transTo(categoryDtos, CategoryOpenDto.class);
            List<CategoryOpenDto> firstLeve = Lists.newArrayList();
            List<CategoryOpenDto> secondLeve = Lists.newArrayList();
            List<CategoryOpenDto> thirdLeve = Lists.newArrayList();
            for (CategoryOpenDto label : labelOpenDtos) {
                if (label.getLevel()== 1) {// 一级类别
                    firstLeve.add(label);
                }
                if (label.getLevel() == 2) {// 二级类别
                    secondLeve.add(label);
                }
                if (label.getLevel() == 3) {// 三级类别
                    thirdLeve.add(label);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("所有的三级分类信息为:{}",thirdLeve);
            }
            Map<Integer, List<CategoryOpenDto>> secondLevelmap = Maps.newHashMap();
            for (CategoryOpenDto labelOpenDto : secondLeve) {// 对二级分类按照父类进行分类

                if (secondLevelmap.containsKey(labelOpenDto.getParentId())) {
                    secondLevelmap.get(labelOpenDto.getParentId()).add(labelOpenDto);
                }else {
                    List<CategoryOpenDto> temp=Lists.newArrayList();
                    temp.add(labelOpenDto);
                    secondLevelmap.put(labelOpenDto.getParentId(), temp);
                }

            }
            if (logger.isDebugEnabled()) {
               logger.debug("二级分类信息列表map:{}",secondLevelmap);
            }
         
            //把二级分类放到对应的一级分类的子集合中
            for (CategoryOpenDto categoryOpenDto : firstLeve) {
                categoryOpenDto.setChildCategoryOpenDtos(secondLevelmap.get(categoryOpenDto.getCategoryId()));
            }
            
            Map<Integer, List<CategoryOpenDto>> thirdLeveLmap = Maps.newHashMap();
            for (CategoryOpenDto labelOpenDto : thirdLeve) {// 对三级分类按照父类进行分类
                if (thirdLeveLmap.containsKey(labelOpenDto.getParentId())) {
                    thirdLeveLmap.get(labelOpenDto.getParentId()).add(labelOpenDto);
                } else {
                    List<CategoryOpenDto> temp = Lists.newArrayList();
                    temp.add(labelOpenDto);
                    thirdLeveLmap.put(labelOpenDto.getParentId(), temp);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("三级分类信息列表map:{}",thirdLeveLmap);
            }
         
            //把三级分类放到对应的二级分类下面
            for (CategoryOpenDto categoryOpenDto : secondLeve) {
                categoryOpenDto.setChildCategoryOpenDtos(thirdLeveLmap.get(categoryOpenDto.getCategoryId()));
            }
            if (logger.isDebugEnabled()) {
                logger.debug("查询到分类后的信息为{}",firstLeve);
            }
            remoteResult.setResult(firstLeve);

        } catch (Exception e) {
            remoteResult.setExceptionStack(e);
            remoteResult.setSuccess(false);
        }
        return remoteResult;
    }

}
